package Demo03;

import org.hibernate.*;

import java.util.List;

public class UserDAOImpl implements UserDAO {
    @Override
    //查询用户列表
    public List<User> selAll() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            //得到sessionFactory
            //得到session
            session = SessionTools.getSession();
            //开启事务
            tx = session.beginTransaction();

            Criteria criteria=session.createCriteria(User.class);
            List<User> list=criteria.list();

            tx.commit();

            return list;
        }catch(Exception e) {
            tx.rollback();
        }finally {
//            session.close();
            //sessionFactory不需要关闭
//			sessionFactory.close();
        }
        return null;
    }
    //保存用户
    @Override
    public void SaveUser(User user) {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            //得到sessionFactory
            //得到session
            session = SessionTools.getSession();
            //开启事务
            tx = session.beginTransaction();

            session.save(user);
            tx.commit();

        }catch(Exception e) {
            tx.rollback();
        }finally {
//            session.close();
            //sessionFactory不需要关闭
//			sessionFactory.close();
        }
    }

    //查询用户,登录功能使用
    @Override
    public String SelUser(String user) {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            //得到sessionFactory
            //得到session
            session = SessionTools.getSession();
            //开启事务
            tx = session.beginTransaction();

            Query query=session.createQuery("select password from User where username = ?");
            query.setParameter(0,user);
            user = (String) query.uniqueResult();


            tx.commit();
        }catch(Exception e) {
            tx.rollback();
        }finally {
//            session.close();
            //sessionFactory不需要关闭
//			sessionFactory.close();
        }
        return user;
    }

}
